<template>
  <div class="knowledge-page">
    <!-- Page Header -->
    <div class="page-header">
      <div>
        <h1 class="page-title">Knowledge Base</h1>
        <p class="page-subtitle">Operations Knowledge Base & AI Q&A</p>
      </div>
      <a-space>
        <a-button @click="showCreateModal">
          <template #icon><PlusOutlined /></template>
          New Document
        </a-button>
        <a-button type="primary" @click="showAIAssistant">
          <template #icon><RobotOutlined /></template>
          AI Assistant
        </a-button>
      </a-space>
    </div>

    <div class="knowledge-content">
      <!-- Sidebar -->
      <div class="knowledge-sidebar">
        <!-- Search -->
        <a-input-search
          v-model:value="searchText"
          placeholder="Search knowledge base..."
          @search="handleSearch"
          style="margin-bottom: 16px"
        />

        <!-- Categories -->
        <a-card title="Categories" size="small" :bordered="false" class="sidebar-card">
          <a-menu
            v-model:selected-keys="selectedCategory"
            mode="inline"
            :style="{ border: 'none' }"
            @select="handleCategorySelect"
          >
            <a-menu-item key="all">
              <AppstoreOutlined />
              All Categories
            </a-menu-item>
            <a-menu-item v-for="cat in categories" :key="cat" :value="cat">
              <FolderOutlined />
              {{ cat }}
            </a-menu-item>
          </a-menu>
        </a-card>

        <!-- Popular Tags -->
        <a-card title="Popular Tags" size="small" :bordered="false" class="sidebar-card">
          <div class="tag-cloud">
            <a-tag
              v-for="tag in popularTags"
              :key="tag.name"
              :color="selectedTags.includes(tag.name) ? 'blue' : 'default'"
              style="cursor: pointer; margin-bottom: 8px"
              @click="toggleTag(tag.name)"
            >
              {{ tag.name }} ({{ tag.count }})
            </a-tag>
          </div>
        </a-card>

        <!-- Quick Stats -->
        <a-card title="Statistics" size="small" :bordered="false" class="sidebar-card">
          <a-statistic
            title="Total Documents"
            :value="stats.totalDocs"
            :value-style="{ fontSize: '20px' }"
          >
            <template #prefix><FileTextOutlined /></template>
          </a-statistic>
          <a-divider style="margin: 12px 0" />
          <a-statistic
            title="This Month"
            :value="stats.thisMonth"
            :value-style="{ fontSize: '16px' }"
          >
            <template #prefix><PlusCircleOutlined /></template>
          </a-statistic>
        </a-card>
      </div>

      <!-- Main Content -->
      <div class="knowledge-main">
        <!-- Filter Bar -->
        <div class="filter-bar">
          <a-space>
            <span>Sort by:</span>
            <a-select v-model:value="sortBy" style="width: 150px" @change="handleSort">
              <a-select-option value="createdAt">Latest</a-select-option>
              <a-select-option value="viewCount">Most Viewed</a-select-option>
              <a-select-option value="likeCount">Most Liked</a-select-option>
              <a-select-option value="title">Title A-Z</a-select-option>
            </a-select>

            <a-select v-model:value="statusFilter" style="width: 120px" @change="handleFilterChange">
              <a-select-option value="all">All Status</a-select-option>
              <a-select-option value="published">Published</a-select-option>
              <a-select-option value="draft">Draft</a-select-option>
            </a-select>
          </a-space>

          <a-button @click="resetFilters" size="small">
            <ClearOutlined /> Reset
          </a-button>
        </div>

        <!-- Document List -->
        <a-spin :spinning="loading">
          <div class="doc-list">
            <div
              v-for="doc in documents"
              :key="doc.id || doc._id"
              class="doc-card"
              @click="viewDocument(doc)"
            >
              <div class="doc-header">
                <h3 class="doc-title">{{ doc.title }}</h3>
                <a-tag v-if="doc.status === 'draft'" color="orange">Draft</a-tag>
                <a-tag v-else color="green">Published</a-tag>
              </div>

              <div class="doc-meta">
                <span class="doc-category">
                  <FolderOutlined />
                  {{ doc.category }}
                </span>
                <span class="doc-author">
                  <UserOutlined />
                  {{ doc.author.username }}
                </span>
                <span class="doc-date">
                  <ClockCircleOutlined />
                  {{ dayjs(doc.createdAt).fromNow() }}
                </span>
              </div>

              <div class="doc-content">
                {{ getContentPreview(doc.content) }}
              </div>

              <div class="doc-tags">
                <a-tag v-for="tag in doc.tags.slice(0, 5)" :key="tag" size="small">
                  {{ tag }}
                </a-tag>
              </div>

              <div class="doc-footer">
                <a-space>
                  <span class="doc-stat">
                    <EyeOutlined /> {{ doc.viewCount }}
                  </span>
                  <span class="doc-stat">
                    <LikeOutlined /> {{ doc.likeCount }}
                  </span>
                </a-space>

                <a-space>
                  <a-button type="link" size="small" @click.stop="editDocument(doc)">
                    <EditOutlined /> Edit
                  </a-button>
                  <a-button type="link" size="small" danger @click.stop="deleteDocument(doc)">
                    <DeleteOutlined /> Delete
                  </a-button>
                </a-space>
              </div>
            </div>

            <a-empty v-if="documents.length === 0" description="No documents found" />
          </div>

          <!-- Pagination -->
          <div class="pagination" v-if="pagination.total > 0">
            <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :show-size-changer="true"
              :show-total="(total) => `Total ${total} documents`"
              @change="handlePageChange"
            />
          </div>
        </a-spin>
      </div>
    </div>

    <!-- Create/Edit Document Modal -->
    <a-modal
      v-model:open="editModalVisible"
      :title="editingDoc ? 'Edit Document' : 'Create Document'"
      width="900px"
      :confirm-loading="submitting"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-item label="Title" name="title" :rules="[{ required: true, message: 'Please enter title' }]">
          <a-input v-model:value="formData.title" placeholder="Enter document title" />
        </a-form-item>

        <a-form-item label="Category" name="category" :rules="[{ required: true, message: 'Please select category' }]">
          <a-select v-model:value="formData.category" placeholder="Select category">
            <a-select-option v-for="cat in categories" :key="cat" :value="cat">
              {{ cat }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="Tags" name="tags">
          <a-select
            v-model:value="formData.tags"
            mode="tags"
            placeholder="Add tags"
            :options="tagOptions"
          />
        </a-form-item>

        <a-form-item label="Content" name="content" :rules="[{ required: true, message: 'Please enter content' }]">
          <a-textarea
            v-model:value="formData.content"
            placeholder="Enter document content (Markdown supported)"
            :rows="12"
            :maxlength="10000"
            show-count
          />
        </a-form-item>

        <a-form-item label="Status" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio value="draft">Draft</a-radio>
            <a-radio value="published">Published</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- AI Assistant Drawer -->
    <a-drawer
      v-model:open="aiDrawerVisible"
      title="AI Assistant"
      width="500"
      placement="right"
    >
      <div class="ai-assistant">
        <div class="chat-messages" ref="chatMessagesRef">
          <div v-for="(msg, index) in chatHistory" :key="index" class="chat-message" :class="msg.type">
            <div class="message-avatar">
              <UserOutlined v-if="msg.type === 'user'" />
              <RobotOutlined v-else />
            </div>
            <div class="message-content">
              <div class="message-text">{{ msg.content }}</div>
              <div class="message-time">{{ dayjs(msg.time).format('HH:mm') }}</div>
              <div v-if="msg.relatedDocs && msg.relatedDocs.length > 0" class="related-docs">
                <a-divider orientation="left" style="font-size: 12px">Related Documents</a-divider>
                <div v-for="doc in msg.relatedDocs" :key="doc.id || doc._id" class="related-doc-item" @click="viewDocument(doc)">
                  <FileTextOutlined />
                  {{ doc.title }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <a-input
            v-model:value="aiQuestion"
            placeholder="Ask AI a question..."
            :disabled="aiLoading"
            @press-enter="askAI"
          >
            <template #suffix>
              <a-button
                type="primary"
                :loading="aiLoading"
                @click="askAI"
                size="small"
              >
                <SendOutlined />
              </a-button>
            </template>
          </a-input>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import {
  PlusOutlined,
  RobotOutlined,
  AppstoreOutlined,
  FolderOutlined,
  FileTextOutlined,
  PlusCircleOutlined,
  ClearOutlined,
  UserOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  LikeOutlined,
  EditOutlined,
  DeleteOutlined,
  SendOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue'
import type { FormInstance } from 'ant-design-vue'
import { useKnowledgeStore } from '@/stores/knowledgeStore'
import { askAI as askAIApi } from '@/api/knowledge'

dayjs.extend(relativeTime)

const knowledgeStore = useKnowledgeStore()

const submitting = ref(false)
const editModalVisible = ref(false)
const aiDrawerVisible = ref(false)
const editingDoc = ref<any>(null)
const formRef = ref<FormInstance>()
const chatMessagesRef = ref<HTMLElement>()

const searchText = ref('')
const selectedCategory = ref<string[]>(['all'])
const selectedTags = ref<string[]>([])
const sortBy = ref('createdAt')
const statusFilter = ref('published')

const formData = reactive({
  title: '',
  category: '',
  tags: [] as string[],
  content: '',
  status: 'draft' as 'draft' | 'published',
})

// Use store state
const loading = computed(() => knowledgeStore.loading)
const documents = computed(() => knowledgeStore.documents)
const categories = computed(() => knowledgeStore.categories)
const popularDocs = computed(() => knowledgeStore.popularDocs)

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
})

// Compute popular tags from documents
const popularTags = computed(() => {
  const tagCounts: Record<string, number> = {}
  documents.value.forEach(doc => {
    doc.tags.forEach(tag => {
      tagCounts[tag] = (tagCounts[tag] || 0) + 1
    })
  })
  return Object.entries(tagCounts)
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 10)
})

const tagOptions = computed(() => popularTags.value.map(t => ({ label: t.name, value: t.name })))

const stats = computed(() => ({
  totalDocs: knowledgeStore.pagination.total,
  thisMonth: documents.value.filter(doc => {
    const createdAt = new Date(doc.createdAt)
    const now = new Date()
    return createdAt.getMonth() === now.getMonth() && createdAt.getFullYear() === now.getFullYear()
  }).length,
}))

const aiQuestion = ref('')
const aiLoading = ref(false)
const chatHistory = ref<any[]>([
  {
    type: 'assistant',
    content: 'Hello! I\'m your AI assistant. Ask me anything about operations and I\'ll help you find relevant knowledge.',
    time: new Date().toISOString(),
  },
])

const getContentPreview = (content: string) => {
  return content.length > 150 ? content.substring(0, 150) + '...' : content
}

const handleSearch = async () => {
  await knowledgeStore.search(searchText.value)
  updatePagination()
}

const handleCategorySelect = async ({ key }: { key: string }) => {
  selectedCategory.value = [key]
  await knowledgeStore.filterByCategory(key)
  updatePagination()
}

const toggleTag = async (tag: string) => {
  const index = selectedTags.value.indexOf(tag)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tag)
  }
  await knowledgeStore.filterByTags(selectedTags.value)
  updatePagination()
}

const handleSort = async () => {
  await loadDocuments()
}

const handleFilterChange = async () => {
  await loadDocuments()
}

const resetFilters = async () => {
  searchText.value = ''
  selectedCategory.value = ['all']
  selectedTags.value = []
  sortBy.value = 'createdAt'
  statusFilter.value = 'published'
  await knowledgeStore.resetFilters()
  updatePagination()
}

const handlePageChange = async (page: number, pageSize: number) => {
  if (pageSize !== pagination.pageSize) {
    await knowledgeStore.changePageSize(pageSize)
  } else {
    await knowledgeStore.changePage(page)
  }
  updatePagination()
}

const loadDocuments = async () => {
  const status = statusFilter.value === 'all' ? undefined : statusFilter.value
  await knowledgeStore.fetchDocuments({ status })
  updatePagination()
}

const updatePagination = () => {
  pagination.current = knowledgeStore.pagination.page
  pagination.pageSize = knowledgeStore.pagination.pageSize
  pagination.total = knowledgeStore.pagination.total
}

const viewDocument = async (doc: any) => {
  await knowledgeStore.fetchDocumentById(doc.id || doc._id)
  message.info(`Viewing: ${doc.title}`)
  // TODO: Navigate to document detail page or show in modal
}

const editDocument = async (doc: any) => {
  await knowledgeStore.fetchDocumentById(doc.id || doc._id)
  editingDoc.value = knowledgeStore.currentDocument
  formData.title = editingDoc.value.title
  formData.category = editingDoc.value.category
  formData.tags = [...editingDoc.value.tags]
  formData.content = editingDoc.value.content
  formData.status = editingDoc.value.status
  editModalVisible.value = true
}

const deleteDocument = (doc: any) => {
  Modal.confirm({
    title: 'Delete Document',
    icon: h(ExclamationCircleOutlined),
    content: `Are you sure you want to delete "${doc.title}"?`,
    okText: 'Delete',
    okType: 'danger',
    cancelText: 'Cancel',
    async onOk() {
      try {
        await knowledgeStore.deleteDocument(doc.id || doc._id)
        message.success('Document deleted successfully')
      } catch (error) {
        message.error('Failed to delete document')
      }
    },
  })
}

const showCreateModal = () => {
  editingDoc.value = null
  formData.title = ''
  formData.category = ''
  formData.tags = []
  formData.content = ''
  formData.status = 'draft'
  editModalVisible.value = true
}

const showAIAssistant = () => {
  aiDrawerVisible.value = true
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    if (editingDoc.value) {
      await knowledgeStore.updateDocument(editingDoc.value.id, {
        title: formData.title,
        category: formData.category,
        tags: formData.tags,
        content: formData.content,
        status: formData.status,
      })
      message.success('Document updated successfully')
    } else {
      await knowledgeStore.createDocument({
        title: formData.title,
        category: formData.category,
        tags: formData.tags,
        content: formData.content,
        status: formData.status,
      })
      message.success('Document created successfully')
    }

    editModalVisible.value = false
    formRef.value?.resetFields()
  } catch (error) {
    console.error('Validation or submission failed:', error)
    message.error('Failed to save document')
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  formRef.value?.resetFields()
  editModalVisible.value = false
}

const askAI = async () => {
  if (!aiQuestion.value.trim()) return

  const userMessage = {
    type: 'user',
    content: aiQuestion.value,
    time: new Date().toISOString(),
  }
  chatHistory.value.push(userMessage)

  const question = aiQuestion.value
  aiQuestion.value = ''
  aiLoading.value = true

  try {
    const response = await askAIApi({ question })

    const aiMessage = {
      type: 'assistant',
      content: response.answer,
      time: new Date().toISOString(),
      relatedDocs: response.relatedDocs || [],
    }
    chatHistory.value.push(aiMessage)

    // Scroll to bottom
    setTimeout(() => {
      if (chatMessagesRef.value) {
        chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
      }
    }, 100)
  } catch (error) {
    message.error('Failed to get AI response')
    const errorMessage = {
      type: 'assistant',
      content: 'Sorry, I encountered an error processing your question. Please try again.',
      time: new Date().toISOString(),
    }
    chatHistory.value.push(errorMessage)
  } finally {
    aiLoading.value = false
  }
}

onMounted(async () => {
  // Fetch initial data
  await Promise.all([
    knowledgeStore.fetchDocuments({ status: statusFilter.value }),
    knowledgeStore.fetchCategories(),
    knowledgeStore.fetchPopularDocs(),
  ])
  updatePagination()
})
</script>

<style scoped lang="scss">
.knowledge-page {
  height: 100%;
  overflow: auto;
  background: #f5f5f5;
}

.page-header {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }

  .page-subtitle {
    margin: 4px 0 0;
    color: #8c8c8c;
    font-size: 14px;
  }
}

.knowledge-content {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 24px;
  padding: 24px;
  align-items: start;
}

.knowledge-sidebar {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .sidebar-card {
    :deep(.ant-card-head) {
      min-height: auto;
      padding: 12px 16px;
    }

    :deep(.ant-card-body) {
      padding: 12px;
    }
  }

  .tag-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
}

.knowledge-main {
  background: white;
  border-radius: 8px;
  padding: 24px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.doc-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.doc-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border-color: #667eea;
  }

  .doc-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .doc-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #262626;
    }
  }

  .doc-meta {
    display: flex;
    gap: 16px;
    margin-bottom: 12px;
    font-size: 13px;
    color: #8c8c8c;

    span {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .doc-content {
    color: #595959;
    line-height: 1.6;
    margin-bottom: 12px;
  }

  .doc-tags {
    margin-bottom: 12px;
  }

  .doc-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;

    .doc-stat {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #8c8c8c;
      font-size: 13px;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.ai-assistant {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px 0;
    margin-bottom: 16px;

    .chat-message {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;

      &.user {
        flex-direction: row-reverse;

        .message-content {
          background: #667eea;
          color: white;
        }
      }

      .message-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
      }

      .message-content {
        max-width: 70%;
        background: #f5f5f5;
        border-radius: 12px;
        padding: 12px;

        .message-text {
          margin-bottom: 4px;
          line-height: 1.6;
        }

        .message-time {
          font-size: 11px;
          color: #8c8c8c;
        }

        .related-docs {
          margin-top: 12px;

          .related-doc-item {
            padding: 8px;
            background: white;
            border-radius: 4px;
            margin-bottom: 8px;
            cursor: pointer;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;

            &:hover {
              background: #e6f7ff;
              color: #1890ff;
            }
          }
        }
      }
    }
  }

  .chat-input {
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
  }
}

@media (max-width: 1024px) {
  .knowledge-content {
    grid-template-columns: 1fr;

    .knowledge-sidebar {
      order: 2;
    }
  }
}
</style>
